package dao.Client;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import model.Client;
import abstractFactory.Factory;

public class ClientDAOJPA implements ClientDAO{
	static EntityManager manager;

	public EntityManager getManager() {
		if(manager == null) {
			manager = Factory.getFactory().createEntityManager();
		}
		return manager;
	}

	public boolean save(Client client){
		try	{
			getManager().getTransaction().begin();
			getManager().persist(client);
			getManager().getTransaction().commit();
			return true;
		}catch (Exception e) {
			System.out.println(e);
			return false;
		}
	}

	public boolean update(Client client){
		try{
			getManager().getTransaction().begin();
			getManager().merge(client);
			getManager().getTransaction().commit();
			return true;
		}catch (Exception e) {
			return false;
		}
	}

	public boolean delete(Client client){

		try {
			Client cli = getManager().find(Client.class,client.getId());
			getManager().getTransaction().begin();
			getManager().remove(cli);
			getManager().getTransaction().commit();
			return true;
		} catch (Exception e) {
			return false;
		}

	}

	public List<Client> getAllClients(){
		Query query = (Query) getManager().createQuery("SELECT c FROM Client c where c.active = 1" );
		@SuppressWarnings("unchecked")
		List<Client> Clients = (List<Client>)query.getResultList();
		return Clients;
	}

	public Long getTotalClients(){
		Query query = (Query) getManager().createQuery("SELECT count(c) FROM Client c where c.active = 1" );
		Long total = (Long) query.getSingleResult();
		return total;
	}

	public Client doLogin(String clientName, String clientPassword){
		try {
			Query query = (Query) getManager().createQuery("SELECT c FROM Client c where c.login = :n and c.password = :p" );
			query.setParameter("n", clientName);
			query.setParameter("p", clientPassword);
			Client client = (Client) query.getSingleResult();
			if(client != null)
				return client;
			else
				return null;
		} 
		catch (Exception e) {	
			return null;				
		}
	}

	public Client getClientById(int id){
		try {
			Client client = getManager().find(Client.class, id);
			return client;
		} 
		catch (Exception e) {	
			return null;				
		}
	}
	
	public boolean getClientByLogin(String clientLogin){
		Query query = (Query) getManager().createQuery("SELECT c FROM Client c where c.login = :n" );
		query.setParameter("n", clientLogin);
		Client client = (Client) query.getSingleResult();
		if(client == null){
			return false;
		}
		return true;
	}
}
